package ks.client.controllers.commands;

import java.util.Collection;

import org.w3c.dom.Document;

import ks.client.kommander.Action;
import ks.client.lobby.Lobby;
import ks.framework.common.Message;

public class ChatCommandController {
	private Lobby lobby;
	
	public ChatCommandController(Lobby l) {
		this.lobby = l;
	}
	
	/**
	 * Just send a public chat message.
	 * 
	 * @param message
	 */
	public void send(String message) {
		String uid = lobby.getKommander().generateUid();
		
		StringBuilder sb = new StringBuilder("<command version=\"1.0\" id=\"" + uid + "\">");
		sb.append("<chat>");
		sb.append("<text>" + message + "</text>");
		sb.append("</chat>");
		sb.append("</command>");
		
		Document d = Message.construct(sb.toString());
		Message m = new Message(d);
		lobby.getUserContext().getClient().sendToServer(m);
	}
	
	/**
	 * Send a public chat message and perform an Action on ack/nack.
	 * 
	 * @param message
	 * @param action
	 */
	public void send(String message, Action action) {
		String uid = lobby.getKommander().generateUid();
		
		StringBuilder sb = new StringBuilder("<command version=\"1.0\" id=\"" + uid + "\">");
		sb.append("<chat>");
		sb.append("<text>" + message + "</text>");
		sb.append("</chat>");
		sb.append("</command>");
		
		lobby.getKommander().addAction(uid, action);
		
		Document d = Message.construct(sb.toString());
		Message m = new Message(d);
		lobby.getUserContext().getClient().sendToServer(m);
	}
	
	/**
	 * Just send a private chat message.
	 * 
	 * @param message
	 * @param players
	 */
	public void send(String message, Collection<String> players) {
		String uid = lobby.getKommander().generateUid();
		
		StringBuilder sb = new StringBuilder("<command version=\"1.0\" id=\"" + uid + "\">");
		sb.append("<chat>");
		for (String player : players)
			sb.append("<playername name=\"" + player + "\"/>");
		sb.append("<text>" + message + "</text>");
		sb.append("</chat>");
		sb.append("</command>");
		
		Document d = Message.construct(sb.toString());
		Message m = new Message(d);
		lobby.getUserContext().getClient().sendToServer(m);
	}
	
	/**
	 * Send a private chat message and perform an Action on ack/nack.
	 * 
	 * @param message
	 * @param players
	 * @param action
	 */
	public void send(String message, Collection<String> players, Action action) {
		String uid = lobby.getKommander().generateUid();
		
		StringBuilder sb = new StringBuilder("<command version=\"1.0\" id=\"" + uid + "\">");
		sb.append("<chat>");
		for (String player : players)
			sb.append("<playername name=\"" + player + "\"/>");
		sb.append("<text>" + message + "</text>");
		sb.append("</chat>");
		sb.append("</command>");
		
		lobby.getKommander().addAction(uid, action);
		
		Document d = Message.construct(sb.toString());
		Message m = new Message(d);
		lobby.getUserContext().getClient().sendToServer(m);
	}
}